package lijiale.project.employee.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lijiale.project.employee.service.EmployeeService;

import lijiale.project.employee.model.EmployeeModel;

import lijiale.project.util.FmtRequest;

//接受请求  获取参数  封装对象  调用方法  返回结果
@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		Object res="";
		switch (req.getParameter("action")) {
		case "reg":
			res=reg(req);
			break;
		case "login":
			res=login(req);
			break;
		default:
			break;
		}
//		resp.getWriter().write(res);
		FmtRequest.write(resp.getWriter(),res);
	}

	
	//定义出下一级 service 的对象
		private EmployeeService service=new EmployeeService();
		
	
	private Object reg(HttpServletRequest req) {
		//封装对象
		String code = req.getParameter("code");
		String pass = req.getParameter("pass");
		String name = req.getParameter("name");
		EmployeeModel model = new EmployeeModel(code,name,pass);
		//调用 下一级 service 中的方法,并返回
		return service.insert(model);
	}

	private Object login(HttpServletRequest req) {
		//获取参数，封装对像
				EmployeeModel model=FmtRequest.parseModel(req, EmployeeModel.class);
				String res=service.login(model);
				if("1".equals(res)) {
					req.getSession().setAttribute("user",service.selectModel(model) );
				}
				return res;		
	}
	
	
}
